#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Create your views here.

from django.http import JsonResponse
from django.shortcuts import render

from django.views import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from job.src.function.basic_opration import *
from job.src.function.record_log import mylog
from markdown.models import MdFiles
from job.views import webPage
from markdown.src import __initData__
from markdown.src.luckysheet_update import redis_obj
from markdown.views.MdView import get_editor
from django.shortcuts import HttpResponse

# redis_obj = db.RedisDB(settings)

# 页面数据初始化加载
class LuckySheetLoadUrl(View):
    context = {}
    context.update(webPage)
    context['has_permission'] = True

    @method_decorator(login_required)
    def get(self, request):
        space = request.GET.get('space', 'common')
        filename = request.GET.get('filename')
        if not filename:
            filename = './static/markdown/common/excel/'
            self.context['next_url'] = f"/markdown/fileList/?path={filename}&space=common"
            self.context['sheet_title'] = 'LuckysheetDemo'
            self.context['sheet_filename'] = 'LuckysheetDemo.xlsx'
        else:
            file = split_path(filename)
            next_path = file[0] + '/'
            # fileCN = MdFiles.objects.filter(upload_name=file[1]).first()
            self.context['next_url'] = "/markdown/fileList/?path=" + next_path + "&space=" + space
            self.context['sheet_title'] = file[2]
            self.context['sheet_filename'] = file[1]
        self.context['filename'] = filename
        return render(request, 'sheetEdit.html', self.context)

    def post(self, request):
        mylog.info("post request")
        gridkey = request.POST.get("gridKey", 'LuckysheetDemo.xlsx')
        mylog.info("gridkey: %s" % gridkey)
        init_json = __initData__.sheetInitData
        # 该判断是为了在用户刚开始上传excel的时候，点击保存数据库之后，从redis再加载一边数据，作为协同使用
        if gridkey:
            redis_json = redis_obj.get_string("sheet:" + gridkey)
            if redis_json != -1:
                redi_json = json.loads(redis_json)
                init_json = json.dumps(redi_json.get("data"))
            else:
                fileExit = MdFiles.objects.filter(upload_name=gridkey).exists()
                if fileExit:
                    fileinfo = MdFiles.objects.filter(upload_name=gridkey).first()
                    filepath = fileinfo.upload_dir + fileinfo.upload_name
                    mylog.info(f"filepath: {filepath}")
                    sheet_json = read_json(filepath)
                    redis_json = json.dumps(sheet_json)
                else:
                    data = {"doc_type": '.xlsx', "space": 'common', "upload_dir": './static/markdown/common/excel/',
            "upload_name": gridkey, "cn_name": '新增的LuckysheetDemo.xlsx'}
                    MdFiles(**data).save()
                    sheet_json = {"data": init_json}
                    demo_path = data['upload_dir'] + data['upload_name']
                    write_json(demo_path, sheet_json)
                    redis_json = json.dumps(sheet_json)
                res = redis_obj.insert_string("sheet:" + gridkey, redis_json)
                redis_obj.set_expireat(gridkey, save_time=3*24*60*60)
                mylog.info(f"inset into redis:{res}")
                init_json = json.dumps(sheet_json.get("data"))
        else:
            gridkey = 'LuckysheetDemo.xlsx'
            res = redis_obj.insert_string("sheet:" + gridkey, json.dumps({"data": init_json}))
            redis_obj.set_expireat(gridkey, save_time=3*24*60*60)
            mylog.info(f"inset into redis:{res}")
            init_json = json.dumps(init_json)
        return HttpResponse('%s' % init_json)


# 保存数据库处理
class LuckySheetSaveDb(View):
    def get(self, request):
        gridKey = request.GET.get("gridKey")
        mylog.info(f"Save file: {gridKey}")
        luckysheet_data = redis_obj.get_string("sheet:" + gridKey)
        if luckysheet_data:
            # MdFiles.objects.filter(upload_name=gridKey).update(text_content=luckysheet_data)
            res = MdFiles.objects.filter(upload_name=gridKey).exists()
            if not res:
                space_path = './static/markdown/common/excel/'
                # gridKey_dec = gridKey.replace('.json', '.xlsx')
                data = {'doc_type': '.xlsx', 'space': 'common', 'upload_dir': space_path, 'upload_name': gridKey,
                        'cn_name': f'保存文件 {gridKey}'}
                MdFiles(**data).save()
                is_dir_exist(space_path)
                filepath = space_path + gridKey
            else:
                file = MdFiles.objects.filter(upload_name=gridKey).first()
                filepath = file.upload_dir + file.upload_name
            sheet_json = json.loads(luckysheet_data)
            write_json(filepath, sheet_json)
            res_info = f"{gridKey} 保存成功!"
        else:
            res_info = "The gridkey does not exists %s" % gridKey
        return JsonResponse({"res_info": res_info})

def getExcelData(request):
    filepath = request.GET.get('filepath')
    file = split_path(filepath)
    exceldata = read_json(filepath)
    sheetdata = exceldata.get('data')
    return JsonResponse({'sheetdata': sheetdata, 'title': file[2]})


def setRedis(request):
    key = request.GET.get('key')
    value = request.GET.get('value')
    res = redis_obj.insert_string(key=key, value=value)
    redis_obj.set_expireat(key, save_time=1 * 24 * 60 * 60)
    return JsonResponse({"status": res, "inser_key": key, "value": value})

def getRedis(request):
    key = request.GET.get('key')
    res = redis_obj.get_string(key=key)
    return HttpResponse(res)

def actRedis(request):
    cmd = request.GET.get('cmd')
    args = cmd.split(' ')
    res = redis_obj.act_command(*args)
    return JsonResponse({"result": res})

# ------------------- edit excel table ：不支持协同--------------

class EditExcel(View):
    context = {}
    context.update(webPage)
    context['has_permission'] = True

    @method_decorator(login_required)
    def get(self, request):
        # name = request.COOKIES.get('name', '')
        # filename = './static/markdown/ljk/test.json'
        space = request.GET.get('space', 'common')
        filename = request.GET.get('filename')
        if not filename:
            filename = './static/markdown/common/excel/LuckysheetDemo.json'
            self.context['next_url'] = "/markdown/fileList/"
            self.context['load_local'] = False
            self.context['sheet_title'] = 'LuckysheetDemo'
        else:
            self.context['load_local'] = True
            content = read_json(filename)
            self.context['option_data'] = json.dumps(content)
            mylog.info(content)
            file = split_path(filename)
            next_path = file[0] + '/'
            self.context['next_url'] = "/markdown/fileList/?path=" + next_path + "&space=" + space
            self.context['sheet_title'] = file[1]
        get_editor(request, filename)   # 更新当前编辑者到数据库
        self.context['space'] = space
        self.context['filename'] = filename
        return render(request, 'tableEdit.html', self.context)

    @csrf_exempt
    def post(self, request):
        mylog.info("post request")
        gridkey = request.POST.get("gridKey", None)
        mylog.info("gridkey: %s" % gridkey)
        init_json = __initData__.sheetInitData
        # 该判断是为了在用户刚开始上传excel的时候，点击保存数据库之后，从redis再加载一边数据，作为协同使用
        if gridkey:

            fileinfo = MdFiles.objects.filter(upload_name=gridkey).first()
            if fileinfo:
                filepath = fileinfo.upload_dir + fileinfo.upload_name
                mylog.info(f"filepath: {filepath}")
                init_json = json.dumps(read_json(filepath))
            else:
                init_json = json.dumps(init_json)
        else:
            init_json = json.dumps(init_json)
        return HttpResponse('%s' % init_json)

@require_POST
@csrf_exempt
def saveSheet(request):
    context = {}
    celldata = request.POST.get('content')
    filepath = request.POST.get('filename')
    space = request.POST.get('space', 'common')
    mylog.info(f"celldata: {celldata}")
    file = split_path(filepath)
    is_dir_exist(file[0])
    filename = file[1]

    # 数据库更新参数
    data = {"doc_type": '.xlsx', "space": space, "upload_dir": file[0] + '/',
            "upload_name": filename, "cn_name": '保存Excel：' + file[2] + '.xlsx'}
    exit_res = MdFiles.objects.filter(upload_name=filename).values().exists()
    if not exit_res:
        MdFiles(**data).save()
    wr = write_json(filepath, json.loads(celldata))
    context['res'] = f"保存结果：{wr}"
    return JsonResponse(context)

@require_POST
@csrf_exempt
def queryEditor(request):
    context = {}
    name = request.COOKIES.get('name', '')
    filepath = request.POST.get('filename')
    # space = request.POST.get('space', 'common')
    file = split_path(filepath)
    mylog.info(file)
    res = MdFiles.objects.filter(upload_name=file[1]).first()
    if res:
        editors = res.cur_editor
        mylog.info(f'editors: {editors}')
        editorlst = editors.split(',')
        # editorlst = editorlst.remove(name) if name in editorlst else editorlst
        if len(editorlst) <= 1:
            context['flag'] = True
            context['tip'] = '当前无其他人共同编辑，可直接保存！'
            context['filename'] = filepath
        else:
            context['flag'] = False
            newfilename = file[0] + '/temp/' + file[2] + '_' + name + file[3]
            cur_editors = ','.join(editorlst)
            cur_editors = cur_editors.lstrip(',')
            context['tip'] = f'当前存在其他人共同编辑，不可直接保存！\r\n将暂存到：{newfilename}\r\n' \
                             f'当前编辑者：{cur_editors}，待他人退出编辑后再合入！'
            context['filename'] = newfilename
    else:
        context['flag'] = True
        context['tip'] = '当前无人编辑，可直接保存！'
        context['filename'] = filepath
    return JsonResponse(context)


def viewDemo(request):
    return render(request, 'LuckysheetDemo.html')